/*
 * n_chuck.c
 *
 *  Created on: Apr 20, 2013
 *      Author: jimmy
 */
#include "n_chuck.h"

#define N_chuck_i2c_addr	0x52 //i2c address
#define N_chuck_i2c_delay_us	 150 // delay after byte trans/recv
#define N_chuck_refresh_ms 250 // might not be needed if we are using the pit to refresh


void n_chuck_init()
{
	n_chuck_reset();
	  // suppose to be for dma3 for delaying between i2c sends and receives
	//i2c_init();
	//pit0_init(); // already called somewhere?? 
}

void n_chuck_down()
{
	set_pac_dir(1); // 1 corresponds to down
}

void n_chuck_up()
{
	set_pac_dir(3); // 3 corresponds to up
}

void n_chuck_left()
{
	set_pac_dir(2);  // 2 corresponds to left
}

void n_chuck_right()
{
	set_pac_dir(4);  // 4 corresponds to right
}


void n_chuck_read()
{ 
	chuck_flag2=1;
	n_chuck_xmit(0xF0, 0x55);
	n_chuck_xmit(0xFB, 0x00);
	n_chuck_xmit(0x00, 0x00);
	
	int data[6] = {0x80,0x80,0,0,0,0}; // ?
	
	i2c_rx(N_chuck_i2c_addr, 6, data);
	
	// now check data to see joystick position
	
		if (data[0] < 50)
		{
			n_chuck_left();
		}
			else if (data[0] > 150)
			{	 
				n_chuck_right();
			}
		
		if (data[1] < 50)
		{
			n_chuck_down();			
		}
			else if(data[1] > 180)
			{
				n_chuck_up();
			}		
chuck_flag2=0;
}

void n_chuck_reset()
{
	set_pac_dir(0);
}


void n_chuck_xmit(int reg, int cmd)
{
	int data[2]={0,0};
	int count;
	
	if (reg!=0)
	{
		data[0]= reg;
		data[1]= cmd;
		count = 2;
	}
	
	else
	{
		data[0]=cmd;
		count=1;		
	}
	
	i2c_tx(N_chuck_i2c_addr, count, data);
	
	dtim0_delay();
		
}





